﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _10_HPBar.GameFrame.System;
using _10_HPBar.Scene.Manager;

namespace _10_HPBar.GameFrame
{
    internal class Game
    {
        bool isOver, isPause;
        long lastTime, fixedTime, currentTime;
        int speed, fps;

        public static Random rand;
        public static InputSystem input;
        public static SceneManager scene;

        protected Game()
        {
            rand = new Random();
            input = new InputSystem();
            scene = new SceneManager();
        }

        public void Play()
        {
            Init();
            fixedTime = DateTime.Now.Ticks;
            lastTime = DateTime.Now.Ticks;
            while (!isOver)
            {
                input.Update();
                Input();
                // 游戏的暂停其实是逻辑的暂停 按键检测和画面更新不能停
                if (!isPause)
                {
                    Update();
                }
                currentTime = DateTime.Now.Ticks;
                if (currentTime - fixedTime > 10_000_000 / speed)
                {
                    if (!isPause)
                    {
                        FixedUpdate();
                    }
                    fixedTime = DateTime.Now.Ticks;
                }
                if (currentTime - lastTime > 10_000_000 / fps)
                {
                    Render();
                    lastTime = DateTime.Now.Ticks;
                }
            }
            End();
        }

        protected virtual void Init()
        {
            Console.CursorVisible = false;
            isOver = false;
            isPause = false;
            speed = 10;
            fps = 30;
            scene.Init();
        }

        protected virtual void Input()
        {
            if (input.IsKeyPressed(ConsoleKey.P))
            {
                // 开关的反转
                isPause = !isPause;
            }
            scene.Input();
        }

        protected virtual void Update()
        {
            scene.Update();
        }

        protected virtual void FixedUpdate()
        {
            scene.FixedUpdate();
        }

        protected virtual void Render()
        {
            scene.Render();
        }

        protected virtual void End()
        {
            scene.End();
        }
    }
}